package com.lq.utils.jdbc;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.log4j.Logger;

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * JDBC工厂 
 * @author 吃人的肉
 * QQ:376870344<br>
 * email:liuqingrou@163.com
 */
public class LqJdbcFactory {
	//数据源连接参数
	private Connection conn = null;
	private Statement stmt = null;
	private PreparedStatement pstmt = null;
	protected Logger log = Logger.getLogger(LqJdbcFactory.class);
	public Integer shiB = null;//事务用到来判断回滚,不等于NULL就回滚
	private ResultSet resultSet=null;
	private int isB=1;//是否自动关闭con
	private LqDBConfig dbConfig=null;
	
	
	/**
	 * 得数据库连接，用完一定要关闭链接
	 * @return
	 */
	public Connection getConn() {
		return conn;
	}

	/**
	 * 1:回滚
	 */
	protected void g(){
		shiB=518;
	}
	
	/**
	 * 不用传参的CON
	 * 直接调用lqjdbc.properties
	 */
	public LqJdbcFactory(LqDBConfig dbConfig){
		try {
			conn=Jdbc.getSDWebgame(null).getConnection();//连接池
			this.dbConfig=dbConfig;
		} catch (Exception e1) {
			log.error("LqJdbc",e1);
			e1.printStackTrace();
			if(conn!=null) {
				try {
					conn.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 传入con
	 * @param c
	 */
	public LqJdbcFactory(Connection c,LqDBConfig dbConfig){
		conn=c;
		this.dbConfig=dbConfig;
	}
	
	/**
	 * 读取其它properties文件
	 * @param properties
	 */
	public LqJdbcFactory(String properties){
		LqConfig conf= new LqConfig(properties);
		try {
			Class.forName(conf.getString("DriverClassName"));
			conn = DriverManager.getConnection(conf.getString("AllUrl").split("\\*\\*\\*")[0],conf.getString("AllUrl").split("\\*\\*\\*")[1],conf.getString("AllUrl").split("\\*\\*\\*")[2]);
		} catch (Exception e) {
			log.error("LqJdbc",e);
			e.printStackTrace();
			if(conn!=null) {
				try {
					conn.close();
				} catch (Exception e2) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 传入参数
	 * @param driverClassName 驱动名
	 * @param url URL格式见lqjdbc.properties
	 */
	public LqJdbcFactory(String driverClassName,String url){
		try {
			Class.forName(driverClassName);
			conn = DriverManager.getConnection(url.split("\\*\\*\\*")[0],url.split("\\*\\*\\*")[1],url.split("\\*\\*\\*")[2]);
		} catch (Exception e) {
			log.error("LqJdbc",e);
			e.printStackTrace();
			if(conn!=null) {
				try {
					conn.close();
				} catch (Exception e2) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 传入参数
	 * @param driverClassName 驱动名
	 * @param url URL格式见lqjdbc.properties
	 */
	public LqJdbcFactory(String driverClassName,String url,LqDBConfig dbConfig){
		this.dbConfig=dbConfig;
		try {
			Class.forName(driverClassName);
			conn = DriverManager.getConnection(url.split("\\*\\*\\*")[0],url.split("\\*\\*\\*")[1],url.split("\\*\\*\\*")[2]);
		} catch (Exception e) {
			log.error("LqJdbc",e);
			e.printStackTrace();
			if(conn!=null) {
				try {
					conn.close();
				} catch (Exception e2) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public int execute(String sql) {
		return execute(sql, 1, new Object[] {});
	}
	public int execute(String sql, Object[] obj) {
		return execute(sql, 1, obj);
	}
	
	/**
	 * EXEC《安全》
	 * @param sql
	 * @param obj
	 * @return
	 */
	public int execute(String sql,int type, Object[] obj) {
		String sqlNew=sql;
		int b = 0;
		try {
			if (obj != null) {
				if(type==2 && obj.length==1) {
					List listObj=new ArrayList();
					
					Pattern reg = Pattern.compile("\\$\\{\\w*\\}");
					Matcher matcher = reg.matcher(sqlNew);
					//String[] keyNames=reg.split(sql,2);
					int c=1;
					Class<? extends Object> cla=null;
					Map<String, Object> map=null;
					JSONObject jsonObject=null;
					if(obj[0] instanceof HashMap) {
						map=(Map) obj[0];
					}else if(obj[0] instanceof JSONObject) {
						jsonObject=(JSONObject) obj[0];
					}else {
						cla=obj[0].getClass();
					}
					while (matcher.find()) {
						String group=matcher.group();
						
						if(obj[0] instanceof HashMap) {
							for (Map.Entry<String, Object> m : map.entrySet()) {
								if(group.indexOf("${"+m.getKey()+"}")!=-1) {
									sqlNew=sqlNew.replace("${"+m.getKey()+"}", "?");
									listObj.add(m.getValue());
									break;
								}
							}
						}else if(obj[0] instanceof JSONObject) {
							for(JSONObject.Entry<String, Object> m : jsonObject.entrySet()) {
								if(group.indexOf("${"+m.getKey()+"}")!=-1) {
									sqlNew=sqlNew.replace("${"+m.getKey()+"}", "?");
									listObj.add(m.getValue());
									break;
								}
							}
						}else {
							for (int i = 0; i < cla.getDeclaredFields().length; i++) {
								Field f=cla.getDeclaredFields()[i];
								boolean flag = f.isAccessible();
								f.setAccessible(true);
								try {
									if(group.indexOf("${"+f.getName()+"}")!=-1) {
										sqlNew=sqlNew.replace("${"+f.getName()+"}", "?");
										listObj.add(f.get(obj[0]));
										f.setAccessible(flag);
										break;
									}
								} catch (IllegalArgumentException e) {
									// TODO Auto-generated catch block
									log.error("LqJdbc",e);
									e.printStackTrace();
								} catch (IllegalAccessException e) {
									// TODO Auto-generated catch block
									log.error("LqJdbc",e);
									e.printStackTrace();
								}
								f.setAccessible(flag);
							}
						}
						c++;
					}
					
					pstmt = conn.prepareStatement(sqlNew);
					for (int i = 1; i <= listObj.toArray().length; i++) {
						setObject(i,listObj.toArray());
					}
				}else {
					pstmt = conn.prepareStatement(sqlNew);
					for (int i = 1; i <= obj.length; i++) {
						setObject(i,obj);
					}
				}
			}
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				insertSqlLog(sql,type, obj);
			}
			long timeStart = System.currentTimeMillis();
			b = pstmt.executeUpdate();
			if (dbConfig.getSqlSuccessTime().equalsIgnoreCase("true")) {
				log.info("查询时间：" + (System.currentTimeMillis() - timeStart) + "ms");
			}
		} catch (Exception e) {
			g();
			insertSqlLog(sql,type, obj);
			log.error("LqJdbc",e);
			e.printStackTrace();
		} finally {
			if (isB==1) {
    			close();
			}
		}
		return b;
	}
	
	/**
	 * EXEC《安全》
	 * @param sql
	 * @param obj
	 * @return
	 */
	public long insertAndReturnId(String sql, Object... obj) {
		long b = 0;
		try {
			pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			if (obj != null) {
				for (int i = 1; i <= obj.length; i++) {
					setObject(i,obj);
				}
			}
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				insertSqlLog(sql,1, obj);
			}
			long timeStart = System.currentTimeMillis();
			pstmt.executeUpdate();
			resultSet = pstmt.getGeneratedKeys();
			if (dbConfig.getSqlSuccessTime().equalsIgnoreCase("true")) {
				log.info("查询时间：" + (System.currentTimeMillis() - timeStart) + "ms");
			}
			while (resultSet.next()) {
			      b = resultSet.getLong(1);
			      //return b;
			}
		} catch (Exception e) {
			g();
			insertSqlLog(sql,1, obj);
			log.error("LqJdbc",e);
			e.printStackTrace();
		} finally {
			if (isB==1) {
				close();
			}
		}
		return b;
	}
	
	/**
	 * EXEC批量《安全》
	 * @param obj
	 */
	public void executeS(Object... obj) {
		try {
			if (obj != null) {
				for (int i = 1; i <= obj.length; i++) {
					setObject(i,obj);
				}
			}
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				insertObjLog(1,obj);
			}
			pstmt.addBatch();
		} catch (Exception e) {
			g();
			insertObjLog(1,obj);
			log.error("LqJdbc",e);
			e.printStackTrace();
			close();
		} finally {
			
		}
			
	}
	
	private void setObject(int i,Object... obj) throws FileNotFoundException, Exception, IOException {
		if(obj[i - 1] instanceof File) {
			pstmt.setBinaryStream(i, new FileInputStream(((File)obj[i - 1])),new FileInputStream(((File)obj[i - 1])).available());
		}else if(obj[i - 1] instanceof FileInputStream) {
			pstmt.setBinaryStream(i, (((FileInputStream)obj[i - 1])),(((FileInputStream)obj[i - 1])).available());
		}else {
			pstmt.setObject(i, obj[i - 1]);
		}
	}
		
	/**
	 * 得到一个数据源(单调此方法需要在操作完成后关闭结果集)
	 * @param sql
	 * @param obj
	 * @return 文件流
	 */
	public ResultSet findResultSet(String sql,Object... obj){
		try {
			pstmt = conn.prepareStatement(sql);
			if (obj != null) {
				for (int i = 1; i <= obj.length; i++) {
					pstmt.setObject(i, obj[i - 1]);
				}
			}
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				insertSqlLog(sql,1, obj);
			}
			resultSet = pstmt.executeQuery();
		} catch (Exception e) {
			g();
			insertSqlLog(sql,1, obj);
			log.error("LqJdbc",e);
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (Exception e2) {
					log.error("LqJdbc",e2);
					e.printStackTrace();
				}
			}
			e.printStackTrace();
		}
		return resultSet;
	}
	
	/**
	 * 查询《安全》
	 * @param sql
	 * @param obj
	 * @return
	 */
	@Deprecated
	public List<ListOrderedMap> find(String sql) {
		return find(sql, 1, new Object[] {});
	}
	public List<ListOrderedMap> find(String sql, Object[] obj) {
		return find(sql, 1, obj);
	}
	public List<ListOrderedMap> find(String sql, Object obj) {
		return find(sql, 1, obj);
	}
	private List<ListOrderedMap> find(String sql,Integer b, Object[] obj) {
		return find(sql, b,1, ListOrderedMap.class, obj);
	}
	private List<ListOrderedMap> find(String sql,Integer b, Object obj) {
		return find(sql, b,2, ListOrderedMap.class, new Object[] {obj});
	}
	public <T> List<T> find(String sql,Class<T> cls){
		return find(sql, 1, 1, cls, new Object[] {});
	}
	public <T> List<T> find(String sql,Class<T> cls,Object[] obj){
		return find(sql, 1, 1, cls, obj);
	}
	public <T> List<T> find(String sql,Class<T> cls,int type,Object[] obj){
		return find(sql, 1, type, cls, obj);
	}
	
	
	
	/**
	 * 查询《安全》
	 * @param sql
	 * @param obj
	 * @return
	 */
	private JSONArray findJSON(String sql,Integer b,int type,Object[] obj) {
		String sqlNew=sql;
		
		if (b==null) {
			b = 1;// 是否关闭连接
		}
		ResultSet rs = null;
		JSONArray list = new JSONArray();
		try {
			if (obj != null) {
				if(type==2 && obj.length==1) {
					List listObj=new ArrayList();
					
					Pattern reg = Pattern.compile("\\$\\{\\w*\\}");
					Matcher matcher = reg.matcher(sqlNew);
					//String[] keyNames=reg.split(sql,2);
					int c=1;
					Class<? extends Object> cla=null;
					Map<String, Object> map=null;
					JSONObject jsonObject=null;
					if(obj[0] instanceof HashMap) {
						map=(Map) obj[0];
					}else if(obj[0] instanceof JSONObject) {
						jsonObject=(JSONObject) obj[0];
					}else {
						cla=obj[0].getClass();
					}
					while (matcher.find()) {
						String group=matcher.group();
						
						if(obj[0] instanceof HashMap) {
							for (Map.Entry<String, Object> m : map.entrySet()) {
								if(group.indexOf("${"+m.getKey()+"}")!=-1) {
									sqlNew=sqlNew.replace("${"+m.getKey()+"}", "?");
									listObj.add(m.getValue());
									break;
								}
							}
						}else if(obj[0] instanceof JSONObject) {
							for(JSONObject.Entry<String, Object> m : jsonObject.entrySet()) {
								if(group.indexOf("${"+m.getKey()+"}")!=-1) {
									sqlNew=sqlNew.replace("${"+m.getKey()+"}", "?");
									listObj.add(m.getValue());
									break;
								}
							}
						}else {
							for (int i = 0; i < cla.getDeclaredFields().length; i++) {
								Field f=cla.getDeclaredFields()[i];
								boolean flag = f.isAccessible();
								f.setAccessible(true);
								try {
									if(group.indexOf("${"+f.getName()+"}")!=-1) {
										sqlNew=sqlNew.replace("${"+f.getName()+"}", "?");
										listObj.add(f.get(obj[0]));
										f.setAccessible(flag);
										break;
									}
								} catch (IllegalArgumentException e) {
									// TODO Auto-generated catch block
									log.error("LqJdbc",e);
									e.printStackTrace();
								}
								f.setAccessible(flag);
							}
						}
						c++;
					}
					pstmt = conn.prepareStatement(sqlNew);
					for (int i = 1; i <= listObj.toArray().length; i++) {
						pstmt.setObject(i, listObj.toArray()[i-1]);
					}
					
				}else {
					pstmt = conn.prepareStatement(sqlNew);
					for (int i = 1; i <= obj.length; i++) {
						pstmt.setObject(i, obj[i - 1]);
					}
				}
				
			}
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				insertSqlLog(sql,type, obj);
			}
			long timeStart = System.currentTimeMillis();
			rs = pstmt.executeQuery();
			if (dbConfig.getSqlSuccessTime().equalsIgnoreCase("true")) {
				log.info("查询时间：" + (System.currentTimeMillis() - timeStart) + "ms");
			}
			ResultSetMetaData rsm = rs.getMetaData();// 获取数据库表结构
			int col = rsm.getColumnCount();// 获取数据库的列数
			while (rs.next()) {
				JSONObject rowData = new JSONObject();
				for (int i = 1; i <= col; i++) {
					if (
							rsm.getColumnTypeName(i).toUpperCase().indexOf("BLOB")!=-1
							||
							rsm.getColumnTypeName(i).toUpperCase().equals("IMAGE")
							||
							rsm.getColumnTypeName(i).toUpperCase().equals("BYTEA")
							) {
						InputStream in = rs.getBinaryStream(i);
						rowData.put(rsm.getColumnName(i).toLowerCase(), in);
					}else if (rsm.getColumnTypeName(i).toUpperCase().equals("CLOB")) {
						if (rs.getObject(i) == null){
							rowData.put(rsm.getColumnName(i).toLowerCase(), "");
						}else{
							Clob clob=(Clob) rs.getObject(i);
							Reader inStream = clob.getCharacterStream();
							char[] c = new char[(int) clob.length()];
							inStream.read(c);
							//data是读出并需要返回的数据，类型是String
							String data = new String(c);
							inStream.close();
							rowData.put(rsm.getColumnName(i).toLowerCase(),data);
						}
					}else {
						if (rs.getObject(i) == null)
							rowData.put(rsm.getColumnName(i).toLowerCase(), "");
						else
							rowData.put(rsm.getColumnName(i).toLowerCase(),rs.getObject(i));
					}
					
				}
				list.add(rowData);
			}
		} catch (Exception e) {
			g();
			insertSqlLog(sql,type, obj);
			log.error("LqJdbc",e);
			e.printStackTrace();
		} finally {
			if (b == 1 && isB==1) {
				if (rs != null) {
					try {
						rs.close();
					} catch (Exception e) {
						log.error("LqJdbc",e);
						e.printStackTrace();
					}
				}
				close();
			}
		}
		return list;
	}
	/**
	 * 查询《安全》
	 * @param sql
	 * @param obj
	 * @return
	 */
	private <T> List<T> find(String sql,Integer b,int type,Class<T> cls, Object[] obj) {
		String sqlNew=sql;
		T objtt = null;
		try {
			objtt = cls.getDeclaredConstructor().newInstance();
		} catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("LqJdbc",e1);
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("LqJdbc",e1);
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("LqJdbc",e1);
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("LqJdbc",e1);
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("LqJdbc",e1);
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("LqJdbc",e1);
		}
		
		if (b==null) {
			b = 1;// 是否关闭连接
		}
		ResultSet rs = null;
		ArrayList<T> list = new ArrayList<T>();
		try {
			if (obj != null) {
				if(type==2 && obj.length==1) {
					List listObj=new ArrayList();
					
					Pattern reg = Pattern.compile("\\$\\{\\w*\\}");
					Matcher matcher = reg.matcher(sqlNew);
					//String[] keyNames=reg.split(sql,2);
					int c=1;
					Class<? extends Object> cla=null;
					Map<String, Object> map=null;
					JSONObject jsonObject=null;
					if(obj[0] instanceof HashMap) {
						map=(Map) obj[0];
					}else if(obj[0] instanceof JSONObject) {
						jsonObject=(JSONObject) obj[0];
					}else {
						cla=obj[0].getClass();
					}
					while (matcher.find()) {
						String group=matcher.group();
						
						if(obj[0] instanceof HashMap) {
							for (Map.Entry<String, Object> m : map.entrySet()) {
								if(group.indexOf("${"+m.getKey()+"}")!=-1) {
									sqlNew=sqlNew.replace("${"+m.getKey()+"}", "?");
									listObj.add(m.getValue());
									break;
								}
							}
						}else if(obj[0] instanceof JSONObject) {
							for(JSONObject.Entry<String, Object> m : jsonObject.entrySet()) {
								if(group.indexOf("${"+m.getKey()+"}")!=-1) {
									sqlNew=sqlNew.replace("${"+m.getKey()+"}", "?");
									listObj.add(m.getValue());
									break;
								}
							}
						}else {
							for (int i = 0; i < cla.getDeclaredFields().length; i++) {
								Field f=cla.getDeclaredFields()[i];
								boolean flag = f.isAccessible();
								f.setAccessible(true);
								try {
									if(group.indexOf("${"+f.getName()+"}")!=-1) {
										sqlNew=sqlNew.replace("${"+f.getName()+"}", "?");
										listObj.add(f.get(obj[0]));
										f.setAccessible(flag);
										break;
									}
								} catch (IllegalArgumentException e) {
									// TODO Auto-generated catch block
									log.error("LqJdbc",e);
									e.printStackTrace();
								}
								f.setAccessible(flag);
							}
						}
						c++;
					}
					
					pstmt = conn.prepareStatement(sqlNew);
					for (int i = 1; i <= listObj.toArray().length; i++) {
						pstmt.setObject(i, listObj.toArray()[i-1]);
					}
					
				}else {
					pstmt = conn.prepareStatement(sqlNew);
					for (int i = 1; i <= obj.length; i++) {
						pstmt.setObject(i, obj[i - 1]);
					}
				}
				
			}
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				insertSqlLog(sql,type, obj);
			}
			long timeStart = System.currentTimeMillis();
			rs = pstmt.executeQuery();
			if (dbConfig.getSqlSuccessTime().equalsIgnoreCase("true")) {
				log.info("查询时间：" + (System.currentTimeMillis() - timeStart) + "ms");
			}
			ResultSetMetaData rsm = rs.getMetaData();// 获取数据库表结构
			int col = rsm.getColumnCount();// 获取数据库的列数
			while (rs.next()) {
				
				if(objtt instanceof JSONObject) {
					JSONObject rowData = new JSONObject();
					for (int i = 1; i <= col; i++) {
						if (
								rsm.getColumnTypeName(i).toUpperCase().indexOf("BLOB")!=-1
								||
								rsm.getColumnTypeName(i).toUpperCase().equals("IMAGE")
								||
								rsm.getColumnTypeName(i).toUpperCase().equals("BYTEA")
						) {
							InputStream in = rs.getBinaryStream(i);
							rowData.put(rsm.getColumnName(i).toLowerCase(), in);
						}else if (rsm.getColumnTypeName(i).toUpperCase().equals("CLOB")) {
							if (rs.getObject(i) == null){
								rowData.put(rsm.getColumnName(i).toLowerCase(), "");
							}else{
								Clob clob=(Clob) rs.getObject(i);
								Reader inStream = clob.getCharacterStream();
								char[] c = new char[(int) clob.length()];
								inStream.read(c);
								//data是读出并需要返回的数据，类型是String
								String data = new String(c);
								inStream.close();
								rowData.put(rsm.getColumnName(i).toLowerCase(),data);
							}
						}else {
							if (rs.getObject(i) == null)
								rowData.put(rsm.getColumnName(i).toLowerCase(), "");
							else
								rowData.put(rsm.getColumnName(i).toLowerCase(),rs.getObject(i));
						}
						
					}
					list.add((T) rowData);
				}else if(objtt instanceof ListOrderedMap){
					ListOrderedMap rowData = new ListOrderedMap();
					for (int i = 1; i <= col; i++) {
						if (
								rsm.getColumnTypeName(i).toUpperCase().indexOf("BLOB")!=-1
								||
								rsm.getColumnTypeName(i).toUpperCase().equals("IMAGE")
								||
								rsm.getColumnTypeName(i).toUpperCase().equals("BYTEA")
						) {
							InputStream in = rs.getBinaryStream(i);
							rowData.put(rsm.getColumnName(i).toLowerCase(), in);
						}else if (rsm.getColumnTypeName(i).toUpperCase().equals("CLOB")) {
							if (rs.getObject(i) == null){
								rowData.put(rsm.getColumnName(i).toLowerCase(), "");
							}else{
								Clob clob=(Clob) rs.getObject(i);
								Reader inStream = clob.getCharacterStream();
								char[] c = new char[(int) clob.length()];
								inStream.read(c);
								//data是读出并需要返回的数据，类型是String
								String data = new String(c);
								inStream.close();
								rowData.put(rsm.getColumnName(i).toLowerCase(),data);
							}
						}else {
							if (rs.getObject(i) == null)
								rowData.put(rsm.getColumnName(i).toLowerCase(), "");
							else
								rowData.put(rsm.getColumnName(i).toLowerCase(),rs.getObject(i));
						}
						
					}
					list.add((T) rowData);
				}else {
					T t = executeResultSet(cls, rs);
	                list.add(t);
				}
				
			}
		} catch (Exception e) {
			g();
			insertSqlLog(sql,type, obj);
			log.error("LqJdbc",e);
			e.printStackTrace();
		} finally {
			if (b == 1 && isB==1) {
				if (rs != null) {
					try {
						rs.close();
					} catch (Exception e) {
						log.error("LqJdbc",e);
						e.printStackTrace();
					}
				}
				close();
			}
		}
		return list;
	}
	
	@Deprecated
	public JSONArray queryForJson(String sql) {
		return queryForJson(sql, 1, new Object[] {});
	}
	public JSONArray queryForJson(String sql, Object[] obj) {
		return queryForJson(sql, 1, obj);
	}
	public JSONArray queryForJson(String sql, Object obj) {
		return queryForJson(sql, 1, obj);
	}
	private JSONArray queryForJson(String sql,Integer b, Object[] obj) {
		return findJSON(sql, b,1,obj);
	}
	private JSONArray queryForJson(String sql,Integer b, Object obj) {
		return findJSON(sql, b,2,new Object[]{obj});
	}
	
	
	
	
	
	
	/**
	 * 关闭
	 */
	public  void close(){
		if (stmt != null){
			try {
				stmt.close();
			} catch (Exception e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		if (pstmt != null){
			try {
				pstmt.close();
			} catch (Exception e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		if (resultSet!=null) {
			try {
				resultSet.close();
			} catch (Exception e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		if (conn != null){
			try {
				conn.close();
			} catch (Exception e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		System.gc();
	}
	
	
	
	private <T> Page<T> findPage(String sql,String sqlCountStr, Integer pageNumber, Integer pageSize,Long totalCount,int type,Class<T> cls, Object[] obj) {
		if (sqlCountStr!=null) {
			totalCount=0l;
			List<ListOrderedMap> listCount=null;
			if(type==1) {
				listCount=find(sqlCountStr,0,obj);
			}else {
				listCount=find(sqlCountStr,0,obj[0]);
			}
			if (listCount.size()>0) {
				ListOrderedMap mapCount=listCount.get(0);
				if (mapCount.size()==1){
					totalCount=Long.valueOf(mapCount.values().toArray()[0].toString());
				}else {
					try {
						StringBuffer eStringBuffer=new StringBuffer();
						eStringBuffer.append("查询总记录数的SQL有问题,只能返回一个数量,不能返回多个字段.\r\n").append("SQL:").append(sqlCountStr);
						throw new LqJdbcException(eStringBuffer.toString());
					} catch (LqJdbcException e) {
						g();
						log.error("LqJdbc",e);
						e.printStackTrace();
					}
				}
			}
		}
		
		if (pageNumber == null || pageNumber<1 ) {
			pageNumber = 1;
		}
		if (pageSize == null || pageSize<1 ) {
			pageSize = 20;
		}
		if (totalCount <= 0) {
			close();
			return new Page<T>();
		}
		long totalPageCount = getTotalPageCount(totalCount, pageSize);
		if (pageNumber > totalPageCount) {
			//pageNumber = Long.valueOf(totalPageCount).intValue();
		}
		int startIndex = Page.getStartOfPage(pageNumber, pageSize);
		StringBuffer exeSql = new StringBuffer(sql);
		if (dbConfig.getDriverClassName().toLowerCase().indexOf("mysql")!=-1) {
			exeSql.append(" limit ").append(startIndex).append(",").append(pageSize);
		}else if (dbConfig.getDriverClassName().toLowerCase().indexOf("postgresql")!=-1) {
			exeSql.append(" limit ").append(pageSize).append(" offset ").append(startIndex);
		}else if (dbConfig.getDriverClassName().toLowerCase().indexOf("oracle")!=-1) {
			exeSql.append("select * from (select row_.*, rownum rownum_  from (").append(sql).append(") row_").append(" where rownum <= ").append(startIndex + pageSize).append(")").append(" where rownum_ >").append(startIndex);
		}else if(dbConfig.getDriverClassName().toLowerCase().indexOf("sqlserver")!=-1){
			/**
			 * 注解：首先利用Row_number()为table1表的每一行添加一个行号，给行号这一列取名'RowNumber' 在over()方法中将'RowNumber'做了升序排列
			 * 然后将'RowNumber'列 与table1表的所有列 形成一个表A
			 * 重点在where条件。假如当前页(currentPage)是第2页，每页显示10个数据(pageSzie)。那么第一页的数据就是第11-20条
			 * 所以为了显示第二页的数据，即显示第11-20条数据，那么就让RowNumber大于 10*(2-1) 即：页大小*(当前页-1)
			 */
			exeSql=new StringBuffer();
			int count=0;
			Pattern p=Pattern.compile("(order by){1}");
			Matcher m=p.matcher(sql.toLowerCase());
			while (m.find()) {
				count++;
			}
			int w=sql.toLowerCase().lastIndexOf("order by");
			if (w!=-1&&count>1) {
				exeSql.append("SELECT TOP ").append(pageSize).append(" * FROM ( ").append(sql.substring(0, w)).append(" ) as row_ WHERE RowNumber > ").append(pageSize*(pageNumber-1)).append(" "+sql.substring(w, sql.length()));
			}else {
				exeSql.append("SELECT TOP ").append(pageSize).append(" * FROM ( ").append(sql).append(" ) as row_ WHERE RowNumber > ").append(pageSize*(pageNumber-1));
			}
		}else if(dbConfig.getDriverClassName().toLowerCase().indexOf("sqlite")!=-1) {
			exeSql.append(" limit ").append(startIndex).append(",").append(pageSize);
		}else if(dbConfig.getDriverClassName().toLowerCase().indexOf("ucanaccess")!=-1){
			exeSql.append(" limit ").append(startIndex).append(",").append(pageSize);
		}else {
			try {
				StringBuffer eStringBuffer=new StringBuffer();
				eStringBuffer.append("不支持这个驱动的分页:").append(dbConfig.getDriverClassName());
				throw new LqJdbcException(eStringBuffer.toString());
			} catch (LqJdbcException e) {
				g();
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		
		List<T> list =null;
		if(type==1) {
			list =find(exeSql.toString(),1,1,cls,obj);
		}else {
			list =find(exeSql.toString(),1,2,cls,obj);
		}
		return new Page<T>(startIndex, totalCount, pageSize, list,Page.DEFAULT_GROUP_PAGE_SIZE);
	}
	
	
	
	
	
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param totalCount 总记录数
	 * @return
	 */
	public <T> Page<T> findPage(String sql, Integer pageNumber, Integer pageSize,Long totalCount,Class<T> cls, Object[] obj) {
		return findPage(sql, null, pageNumber, pageSize, totalCount,1, cls, obj);
	}
	public <T> Page<T> findPage(String sql, Integer pageNumber, Integer pageSize,Long totalCount,Class<T> cls, Object obj) {
		return findPage(sql, null, pageNumber, pageSize, totalCount,2, cls, new Object[] {obj});
	}
	
	@Deprecated
	public <T> Page<T> findPage(String sql, Integer pageNumber, Integer pageSize,Long totalCount,Class<T> cls) {
		return findPage(sql, null, pageNumber, pageSize, totalCount, 1,cls, new Object[] {});
	}
	
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber1 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param sqlCount 得总记录数SQL
	 * @return
	 */
	public <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Class<T> cls,Object[] obj){
		return findPage(sql, sqlCount, pageNumber, pageSize, 0l,1, cls, obj);
	}
	public <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Class<T> cls,Object obj){
		return findPage(sql, sqlCount, pageNumber, pageSize, 0l,2, cls, new Object[] {obj});
	}
	
	@Deprecated
	public <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Class<T> cls){
		return findPage(sql, sqlCount, pageNumber, pageSize, 0l,1, cls, new Object[] {});
	}
	
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param totalCount 总记录数
	 * @return
	 */
	public Page<ListOrderedMap> findPage(String sql, Integer pageNumber, Integer pageSize,Long totalCount, Object[] obj) {
		return findPage(sql, null, pageNumber, pageSize, totalCount, obj);
	}
	public Page<ListOrderedMap> findPage(String sql, Integer pageNumber, Integer pageSize,Long totalCount, Object obj) {
		return findPage(sql, null, pageNumber, pageSize, totalCount, obj);
	}
	public Page<JSONObject> queryPageForJson(String sql, Integer pageNumber, Integer pageSize,Long totalCount, Object[] obj) {
		return queryPageForJson(sql, null, pageNumber, pageSize, totalCount, obj);
	}
	public Page<JSONObject> queryPageForJson(String sql, Integer pageNumber, Integer pageSize,Long totalCount, Object obj) {
		return queryPageForJson(sql, null, pageNumber, pageSize, totalCount, obj);
	}
	
	@Deprecated
	public Page<ListOrderedMap> findPage(String sql, Integer pageNumber, Integer pageSize,Long totalCount) {
		return findPage(sql, null, pageNumber, pageSize, totalCount, new Object[] {});
	}
	@Deprecated
	public Page<JSONObject> queryPageForJson(String sql, Integer pageNumber, Integer pageSize,Long totalCount) {
		return queryPageForJson(sql, null, pageNumber, pageSize, totalCount, new Object[] {});
	}
	
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber1 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param sqlCount 得总记录数SQL
	 * @return
	 */
	public Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object[] obj){
		return findPage(sql, sqlCount, pageNumber, pageSize, 0l, obj);
	}
	public Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object obj){
		return findPage(sql, sqlCount, pageNumber, pageSize, 0l, obj);
	}
	public Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object[] obj){
		return queryPageForJson(sql, sqlCount, pageNumber, pageSize, 0l, obj);
	}
	public Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object obj){
		return queryPageForJson(sql, sqlCount, pageNumber, pageSize, 0l, obj);
	}
	@Deprecated
	public Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount){
		return findPage(sql, sqlCount, pageNumber, pageSize, 0l, new Object[] {});
	}
	@Deprecated
	public Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,String sqlCount){
		return queryPageForJson(sql, sqlCount, pageNumber, pageSize, 0l, new Object[] {});
	}
	
	private Page<ListOrderedMap> findPage(String sql,String sqlCountStr, Integer pageNumber, Integer pageSize,Long totalCount, Object[] obj) {
		return findPage(sql, sqlCountStr, pageNumber, pageSize, totalCount,1, ListOrderedMap.class, obj);
	}
	private Page<ListOrderedMap> findPage(String sql,String sqlCountStr, Integer pageNumber, Integer pageSize,Long totalCount, Object obj) {
		return findPage(sql, sqlCountStr, pageNumber, pageSize, totalCount,2, ListOrderedMap.class, new Object[] {obj});
	}
	private Page<JSONObject> queryPageForJson(String sql,String sqlCountStr, Integer pageNumber, Integer pageSize,Long totalCount, Object[] obj) {
		return findPage(sql, sqlCountStr, pageNumber, pageSize, totalCount, 1,JSONObject.class, obj);
	}
	private Page<JSONObject> queryPageForJson(String sql,String sqlCountStr, Integer pageNumber, Integer pageSize,Long totalCount, Object obj) {
		return findPage(sql, sqlCountStr, pageNumber, pageSize, totalCount,2, JSONObject.class, new Object[] {obj});
	}
	
	
	
	
	
	
	
	
	/**
	 * 取总页数.
	 */
	private long getTotalPageCount(long totalCount, int pageSize) {
		if (totalCount % pageSize == 0)
			return totalCount / pageSize;
		else
			return totalCount / pageSize + 1;
	}
	
	//创建语句类型；  
    private final int entitySave=0;
    private final int entityUpdate=1;
    private final int entityDelete=2;
	
    public int save(Object obj){
    	return setObject(obj,entitySave);
    }
    public int update(Object obj){
    	return setObject(obj, entityUpdate);
    }
    public int delete(Object obj){
    	return setObject(obj, entityDelete);
    }
    
    
    protected int setObject(Object obj,int type){
    	String tableName="";//表名
    	//-----------------------------------插入--------------------------
 		String str1 = "";//有几个属性。
 		String str2 = "";//有几个待插入的位置
 		//-----------------------------------更新--------------------------
 		String strUpdateSql="";
 		String strUpdateWhereSql="";
 		Object strObjectUpdate = null;
 		//-----------------------------------删除--------------------------
 		String strDelWhereSql="";
 		Object strDelObject=null;
 		
 		List<Object> objList=new ArrayList<Object>();
    	Class<? extends Object> cla=obj.getClass();
    	Annotation an=cla.getAnnotation(Table.class);
    	if (an==null) {
    		try {
    			StringBuffer eStringBuffer=new StringBuffer();
    			eStringBuffer.append("没有给实体类").append(obj).append("配制注解@Table(name=)__name=表名");
				throw new LqJdbcException(eStringBuffer.toString());
			} catch (LqJdbcException e) {
				g();
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
			return 0;
		}
    	for (Method method : an.annotationType().getDeclaredMethods()) {
            if (!method.isAccessible()) {
            //if (!method.canAccess(null)) {
                method.setAccessible(true);
            }
            Object invoke = null;
			try {
				invoke = method.invoke(an);
			} catch (IllegalAccessException e) {g();
				log.error("LqJdbc",e);
				e.printStackTrace();
			} catch (IllegalArgumentException e) {g();
				log.error("LqJdbc",e);
				e.printStackTrace();
			} catch (InvocationTargetException e) {g();
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
			if (method.getName().equals("name")) {
				tableName=invoke+"";
			}
            //System.out.println("invoke methd " + method.getName() + " result:" + invoke);
//            if (invoke.getClass().isArray()) {
//                Object[] temp = (Object[]) invoke;
//                for (Object o : temp) {
//                    System.out.println(o);
//                }
//            }
        }
    	
        for (int i = 0; i < cla.getDeclaredFields().length; i++) {
        	Field f=cla.getDeclaredFields()[i];
        	Annotation[] annotations=f.getDeclaredAnnotations();
        	Column column=null;
        	for(Annotation annotation : annotations){
        		if(annotation!=null) {//没有配制不管它,不是映射字段
        			if(annotation instanceof Column) {
        				column=(Column) annotation;
        			}
            	}
        	}
        	
    		if(type==entitySave){
    			str1 += column.column() + ",";
    			str2 += "? ,";
    			try {
    				boolean flag = f.isAccessible();
    				f.setAccessible(true);
					objList.add(f.get(obj));
					f.setAccessible(flag);
				} catch (IllegalAccessException e1) {g();
					log.error("LqJdbc",e1);
					e1.printStackTrace();
				} catch (IllegalArgumentException e1) {g();
					log.error("LqJdbc",e1);
					e1.printStackTrace();
				}
    		}else if(type==entityUpdate){
    			Annotation anId=f.getAnnotation(Id.class);
    	    	if (anId!=null) {//ID
					strUpdateWhereSql+=column.column()+"=?";
					try {
						boolean flag = f.isAccessible();
	    				f.setAccessible(true);
						strObjectUpdate=f.get(obj);
						f.setAccessible(flag);
					} catch (IllegalAccessException e) {g();
						log.error("LqJdbc",e);
						e.printStackTrace();
					} catch (IllegalArgumentException e) {g();
						log.error("LqJdbc",e);
						e.printStackTrace();
					}
				}else {
					strUpdateSql+=column.column()+"=?,";
					try {
						boolean flag = f.isAccessible();
	    				f.setAccessible(true);
						objList.add(f.get(obj));
						f.setAccessible(flag);
					} catch (IllegalAccessException e1) {g();
						log.error("LqJdbc",e1);
						e1.printStackTrace();
					} catch (IllegalArgumentException e1) {g();
						log.error("LqJdbc",e1);
						e1.printStackTrace();
					}
				}
    			
    		}else if(type==entityDelete){
    			Annotation anId=f.getAnnotation(Id.class);
    	    	if (anId!=null) {//ID
					strDelWhereSql+=column.column()+"=?";
					try {
						boolean flag = f.isAccessible();
	    				f.setAccessible(true);
						strDelObject=f.get(obj);
						f.setAccessible(flag);
					} catch (IllegalAccessException e) {g();
						log.error("LqJdbc",e);
						e.printStackTrace();
					} catch (IllegalArgumentException e) {g();
						log.error("LqJdbc",e);
						e.printStackTrace();
					}
				}
    		}
    		
    		
		}
       
        
        if(type==entitySave){
        	// 拼成的字符串最后面多了一个逗号。所以截取除了最后一个字符之外的其他字符
        	str1 = str1.substring(0, str1.length() - 1);
        	str2 = str2.substring(0, str2.length() - 1);
        	//System.out.println(str1 + "  " + str2);
		}else if(type==entityUpdate){
			if (strObjectUpdate==null) {
				try {
					throw new LqJdbcException("没有给实体类"+obj+"中的ID配制注解@Id");
				} catch (LqJdbcException e) {g();
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
				return 0;
			}
			strUpdateSql = strUpdateSql.substring(0, strUpdateSql.length() - 1);
			objList.add(strObjectUpdate);
		}else if(type==entityDelete){
			if (strDelObject==null) {
				try {
					throw new LqJdbcException("没有给实体类"+obj+"中的ID配制注解@Id");
				} catch (LqJdbcException e) {g();
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
				return 0;
			}
			objList.add(strDelObject);
		}
    	int b=1;
    	String sql = null;
		if (type == entitySave) { // save
			sql = "insert into  " + tableName + " (" + str1 + ")   values (" + str2 + ")";
		} else if (type == entityUpdate) { // update
			sql = "update " + tableName + " set "+strUpdateSql+" where "+strUpdateWhereSql; 
		} else if (type == entityDelete) {// delete
			sql = "delete from " + tableName + "  where  "+strDelWhereSql;
		}
		log.info(sql);
    	try {
	        PreparedStatement  ps= conn.prepareStatement(sql);
	        for(int i=0;i<objList.size();i++){
	           ps.setObject(i+1,objList.get(i));
	        }
	        ps.executeUpdate();  
    	}catch(Exception e){
    		g();
    		b=0;
    		try {conn.rollback();} catch (Exception e1) {
    			log.error("LqJdbc",e1);
    			e1.printStackTrace();
    		}
    		log.error("LqJdbc",e);
			e.printStackTrace();
    	}finally {
    		if (isB==1) {
    			close();
			}
    	}
    	return b;
    }
    
    protected static <T> T executeResultSet(Class<T> cls, ResultSet rs) throws InstantiationException, IllegalAccessException, Exception {
    	//T obj = cls.newInstance();
    	T obj=null;
		try {
			obj = (T) cls.getDeclaredConstructor().newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        ResultSetMetaData rsm = rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if(!field.isAccessible()) {
            //if (!field.canAccess(null)) {
            	field.setAccessible(true);//类中的成员变量为private,故必须进行此操作
            }
            Column zd = field.getAnnotation(Column.class);
            String fieldName=null;
            if (zd!=null) {
            	fieldName = zd.column();
			}else {
				fieldName = field.getName();
			}
            for (int j = 1; j <= columnCount; j++) {
                String columnName = rsm.getColumnName(j);
                if (zd!=null && fieldName.equalsIgnoreCase(columnName)) {//如果注解存在，按注解字段名执行
                    Object value = rs.getObject(j);
                    if (value instanceof BigDecimal) {
                    	//field.set(obj, ((BigDecimal) value).doubleValue());
                    	field.set(obj, value);
					}else {
						field.set(obj, value);
					}
                    break;
                }else if(zd==null) {
                	if(fieldName.equalsIgnoreCase(xhxCap(columnName))) {//如果去下滑线大写存在，按去下滑线大写字段字执行
                		Object value = rs.getObject(j);
                        if (value instanceof BigDecimal) {
                        	//field.set(obj, ((BigDecimal) value).doubleValue());
                        	field.set(obj, value);
    					}else {
    						field.set(obj, value);
    					}
                        break;
                	}else if(fieldName.equalsIgnoreCase(columnName)) {//如果以上都不存在，按属性名等字段名执行
                		Object value = rs.getObject(j);
                        if (value instanceof BigDecimal) {
                        	//field.set(obj, ((BigDecimal) value).doubleValue());
                        	field.set(obj, value);
    					}else {
    						field.set(obj, value);
    					}
                        break;
                	}else {
                		//没有匹配到当前字段，实体类中不存在。
                	}
                }
            }
        }
        return obj;
    }
    
    protected void insertSqlLog(String sql,int type,Object[] obj){
    	StringBuffer sqlSB=new StringBuffer("SQL语句:");
		log.info(sqlSB.append(sql.replaceAll("\r\n", " ")));
		insertObjLog(type,obj);
		StringBuffer allSB=new StringBuffer("完整SQL:");
		if(type==2 && obj.length==1) {
			allSB.append(Jdbc.sqlRender(sql, obj[0]));
		}else {
			allSB.append(Jdbc.sqlRender(sql, obj));
		}
		log.info(allSB);
    }
    
    protected void insertObjLog(int type,Object[] obj){
		StringBuffer csSB=new StringBuffer("SQL参数:");
		
		if(type==2 && obj.length==1) {
			
			if(obj[0] instanceof HashMap) {
				Map<String,Object> map=(Map) obj[0];
				for (Map.Entry<String, Object> m : map.entrySet()) {
					csSB.append(m.getValue()).append("___");
				}
			}else if(obj[0] instanceof JSONObject) {
				JSONObject jsonObject=(JSONObject) obj[0];
				for(JSONObject.Entry<String, Object> m : jsonObject.entrySet()) {
					csSB.append(m.getValue()).append("___");
				}
			}else {
				Class<? extends Object> cla=obj[0].getClass();
				for (int i = 0; i < cla.getDeclaredFields().length; i++) {
					Field f=cla.getDeclaredFields()[i];
					boolean flag = f.isAccessible();
					f.setAccessible(true);
					try {
						csSB.append(f.get(obj[0])).append("___");
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						log.error("LqJdbc",e);
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						log.error("LqJdbc",e);
						e.printStackTrace();
					}
					f.setAccessible(flag);
				}
			}
				
		}else {
			for (int i = 0; i < obj.length; i++) {
				csSB.append(obj[i]).append("___");
			}
		}
		log.info(csSB);
		
    }
    
    
    /**
     * 下划线转去掉,后一个字母转大写
     * @param str
     * @return
     */
    protected static String xhxCap(String str){
    	String[] col=str.split("_");
    	StringBuffer sBuffer=new StringBuffer();
    	for (int j = 0; j < col.length; j++) {
    		if (j==0) {
    			sBuffer.append(col[j]);
			}else {
				sBuffer.append(col[j]);
			}
		}
    	return sBuffer.toString();
    }
    
    
    /**
	 * 批量操作
	 * @param sql
	 * @param piLiang
	 * @return
	 */
	public int[] piliang(String sql,LqPiLiang piLiang){
		return piliang(sql, piLiang, true);
	}
	
	/**
	 * 批量操作
	 * @param sql
	 * @param piLiang
	 * @return
	 */
	public int[] piliang(String sql,LqPiLiang piLiang,boolean auto){
		isB=0;
		int[] c = null;
		try {
			if(auto) {
				conn.setAutoCommit(false);
			}
			pstmt = conn.prepareStatement(sql);
			if (dbConfig.getSqlLog().equalsIgnoreCase("true")) {
				StringBuffer sqlSB=new StringBuffer("SQL语句:");
				log.info(sqlSB.append(sql.replaceAll("\r\n", " ")));
			}
			piLiang.piliang(this);
			long timeStart = System.currentTimeMillis();
			c=pstmt.executeBatch();
			if(auto) {
				conn.commit();
				conn.setAutoCommit(true);
			}
			if (dbConfig.getSqlSuccessTime().equalsIgnoreCase("true")) {
				log.info("查询时间：" + (System.currentTimeMillis() - timeStart) + "ms");
			}
		} catch (Exception e) {
			log.error("LqJdbc",e);
			e.printStackTrace();
		}finally{
			close();
		}
		return c;
	}
    
	
	/**
	 * 操作结果集
	 * @param resultSet
	 */
	public void operationResultSet(LqResultSet resultSet){
		try {
			resultSet.getResultSet(this);
		} catch (Exception e) {
			try {conn.rollback();} catch (Exception e1) {
				log.error("LqJdbc",e1);
				e1.printStackTrace();
			}
			log.error("LqJdbc",e);
			e.printStackTrace();
		}finally{
			close();
		}
	}
	
	
	/**
	 * 事务操作
	 * @param shiWu
	 * @return
	 */
	public int shiwu(LqShiWu shiWu){
		try {
			isB=0;
			conn.setAutoCommit(false);//禁止自动提交，设置回滚点
			shiWu.shiwu(this);
			if (shiB!=null) {
				try {conn.rollback();} catch (Exception e1) {
					log.error("LqJdbc",e1);
					e1.printStackTrace();
				}
			}else {
				conn.commit();
				conn.setAutoCommit(true);
			}
		} catch (Exception e) {
			try {conn.rollback();} catch (Exception e1) {
				log.error("LqJdbc",e1);
				e1.printStackTrace();
			}
			log.error("LqJdbc",e);
			e.printStackTrace();
		}finally{
			close();
		}
		if (shiB==null) {
			shiB=1;
		}
		return shiB;
	}
    
	
}
